<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use app\common\library\Upload;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    public function getvideo(){

        $info['video']='https://oa.stp1.cn:84/upload/720P.mp4';
        $info['excel']='https://oa.stp1.cn:84/upload/demo.xlsx';
        $this->success('返回成功',$info);

    }

    /**
     * 获取所有的商户
     */
    public function getallmerch(){

        $merch=Db::name('aa_merch')->select();

        $types=Db::name('aa_types')->select();

        $money=Db::name('aa_money')->select();

        $this->success('返回成功',['merch'=>$merch,'types'=>$types,'money'=>$money]);
    }

    /*
     * 获取所有的用户
     */
    public function getalluser(){
        //32
        $list=Db::query("select id,name,avatar,mobile,nickname from cmf_user where   merch_id = 0 and  username != ' ' ");

        $this->success('返回成功',$list);

    }

    //今天时间
    public function gettime()
    {

        $list=date('ymd');
        $this->success('历史版本',$list);

    }

    //添加店铺
    public function addmerch(){

        $title=$this->request->post('title');

        if(empty($title)){
            $this->error('请输入店铺名称');
        }

        if(Db::name('aa_merch')->where('title',$title)->find()){
            $this->error('店铺名称已存在');
        }

        Db::name('aa_merch')->data(['title'=>$title])->insert();

        $this->success('添加成功');

    }

    /**
     * 获取 cmf_desc_icons 标签
     */

    public function getdescicons(){

        $list=Db::name('desc_icons')->order('weigh desc')->select();

        $this->success('标签',$list);

    }


    /**
     * 上传文件
     */

    public function uploadexcel(){


        $file = $this->request->file('file');

        $id=$this->request->param('id');

        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $files=$attachment->url;

        $case=Db::name('aa_case')->alias('a')
            ->join('cmf_quotation b','a.q_id=b.id')
            ->where(['a.id'=>$id])
            ->field('a.*,b.order,b.id as quotation_id')->find();

        $list=Db::name('quotaion_log')->alias('a')
            ->join('cmf_catefrolist b','a.catefrolist_id=b.id')
            ->where(['a.quotation_id'=>$case['quotation_id'],'a.seesyatus'=>1])
            ->field('a.*,b.name')
            ->select();


//            print_r($list);

        // 假设要读取的 Excel 文件路径
        $filePath = './'.$files;


        // 加载 Excel 文件
        $spreadsheet = IOFactory::load($filePath);
        // 获取活动工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 获取工作表的最大行数
        $highestRow = $sheet->getHighestRow();
        // 初始化变量
        $highestColumnWithValues = 'A'; // 假设至少有 A 列有值

        // 遍历每一列，从 A 列开始

        $counta=0;
        for ($col = 'A'; ; $col++) {
            $hasValue = false; // 标记当前列是否有值
            $row = 4;
            for ($row = 4; $row <= 4; $row++) {
                $cellValue = $sheet->getCell($col . $row)->getValue();
                if ($cellValue !== null && trim($cellValue) !== '') { // 检查是否有值
                    $hasValue = true;
                    break;
                }
            }
            if (!$hasValue) {
                break; // 如果当前列没有值，退出循环
            }

            $counta++;
            $highestColumnWithValues = $col; // 更新有值的最高列
        }

        // 从第 3 行开始获取数据到数组
        $data = [];

        $rowData = [];

        $row = 3;
        //除开通用参数
        for ($col = 12; $col <= $counta; $col++) {
            $cell = $sheet->getCellByColumnAndRow($col, $row);
            $value = $cell->getValue();
            if ($value instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
                $value = $value->getPlainText();
            }
            $rowData[] = $value;
        }
        $data[] = $rowData;

        $arrays=[];
        foreach ($list as $li) {
            $array=[];

            $array['title']=$li['catefrolist_name'];
            $array['gid']=$li['catefrolist_id'];
            $array['size']=$li['size'];
            $array['status']=0;
            $array['set']='';
            $array['money']=$li['money'];
            $array['type']=$li['type'];
            $array['id']=$li['id'];
            $arrays[]=$array;

        }


//        print_r($highestRow);
//        echo "---------";
        // 输出读取的数据（可根据需求处理数据）

        $rowDatas=[];
        $allmoney=0;
        for ($row = 5; $row <= $highestRow; $row++){
            $rowData = [];
            $rowData=[];
            $more=[];

            for ($col = 1; $col <= $counta; $col++) {
                $cell = $sheet->getCellByColumnAndRow($col, $row);
                $value = $cell->getValue();

                if ($value instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
                    $value = $value->getPlainText();
                }

                if ($col<12){
                    $rowData[] = $value;
                }else{
                    $coun=$col-12;
                    $arrays[$coun]['set']=$value;
                    if  ($value == '是'){
                        $allmoney+=$arrays[$coun]['money'];
                    }

                    $more[]=$arrays[$coun];
                }

            }

//                print_r($rowData);
//                echo "---------";


            $rowData['more']=$more;

            $rowDatas[]=$rowData;

        }
        //最后的数据；  搭配
//            print_r($rowDatas);
        $a=0;
        foreach ($rowDatas as $aa=>$array) {
            $adddata=[];
            $adddata['caseid']=$id;
            $adddata['title']=$array['0'];
            $adddata['code']=$array[1];
            $adddata['spu']=$array[2];
            $adddata['sku']=$array[3];
            $adddata['title_b']=$array[4];
            $adddata['color1']=$array[5];
            $adddata['color2']=$array[6];
            $adddata['size']=$array[7];
            $adddata['sex']=$array[8];
            $adddata['colorpro']=$array[9];
            $adddata['desc']=$array[10];
            $adddata['more']=serialize($array['more']);
            $adddata['createtime']=time();
            $adddata['updatetime']=time();

            if ($adddata['title']){

                $dp=1;

                foreach ($array['more'] as $more){
                    if ($more['set']=='是'){
                        $dp=0;
                    }
                }


                $adddata['typetie']=$dp;

                Db::name('newphoto')->insert($adddata);

                $a++;
            }

        }

        Db::name('aa_case')->where(['id'=>$id])->setInc('count',$a);
        Db::name('aa_case')->where(['id'=>$id])->update(['plan'=>1]);

        $this->success('ok');





    }



}
